// pages/takePhoto/result/index.js
// wx.cloud.init({
//   env:'magic-2gl01tcyef44c307'
// })
const db = wx.cloud.database()
const _=db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    theme:getApp().globalData.presentTheme,
    themeName:getApp().globalData.presentTheme.midColor.match(/wux-(\S*)/)[1],
    avatar:getApp().globalData.userInfo.avatarUrl,
    nickname:getApp().globalData.userInfo.nickName,
    charge:false,
    visible1: false,
    visible2: false,
    skinData:'',
    skinGlobalData:[],
    current: 'tab1',
    tabs: [
      {
        key: '美白方案',
        title: '美白方案',
        content: [{
          layoutPicture:'http://cdn.skyvow.cn/logo.png',
          productName:'1-1',
          indication:'',
        },{
          layoutPicture:'http://cdn.skyvow.cn/logo.png',
          productName:'1-2',
          indication:'',
        }],
      },
      {
        key: '护肤方案',
        title: '护肤方案',
        content: [{
          layoutPicture:'http://cdn.skyvow.cn/logo.png',
          productName:'2-1',
          indication:'',
        },{
          layoutPicture:'http://cdn.skyvow.cn/logo.png',
          productName:'2-2',
          indication:'',
        }],
      },
      // {
      //   key: 'tab3',
      //   title: 'Tab 3',
      //   content: 'Content of tab 3',
      // },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.book()
    let that = this
    const eventCannel = this.getOpenerEventChannel()
    eventCannel.on("face_list",res=>{
      console.log("来自 componText 页面的数据",res) //{ data: '我是来自 componText 页面的数据' }
      that.dealFaceInfo(res.data)
      that.setData({
        ['skinData.age']:res.data.age,
       ['skinData.gender']:res.data.gender,
        theme:getApp().globalData.presentTheme,
        themeName:getApp().globalData.presentTheme.midColor.match(/wux-(\S*)/)[1],
        avatar:getApp().globalData.userInfo.avatarUrl,
        nickname:getApp().globalData.userInfo.nickName,
        cost:getApp().globalData.charge
      })
    })
    // wx.getStorage({
    //   key: 'skinData',
    //   success: function(res) {
    //     console.log("来自缓存的数据",res.data)
        // that.setData({
        //   age:res.data.age,
        //   gender:res.data.gender,
        //   theme:getApp().globalData.presentTheme,
        //   themeName:getApp().globalData.presentTheme.midColor.match(/wux-(\S*)/)[1],
        //   avatar:getApp().globalData.userInfo.avatarUrl,
        //   nickname:getApp().globalData.userInfo.nickName,
        // })
    //     that.dealFaceInfo(res.data)
    //   },
    // })

  },
  // "requestPayment:fail parameter error: parameter.timeStamp should be String instead of Undefined;parameter.nonceStr should be String instead of Undefined;parameter.package should be String instead of Undefined;parameter.signType should be String instead of Undefined;parameter.paySign should be String instead of Undefined;"
  pay:function(e){
    let orderid = this.randomWord()
    let that = this
    console.log(orderid)
    wx.cloud.callFunction({
      name: 'pay_test',
      data:{
        outTradeNo:orderid
      },
      success: res => {
        console.log(res)
        const payment = res.result.payment
        wx.requestPayment({
          ...payment,
          success (res) {
            console.log('pay success', res)
            let data = that.data.skinData
            data.outTradeNo = orderid
            data.count=getApp().globalData.userInfo.amount+1
            db.collection("FaceInfo").add({
              data:data
            }).then(res=>{
              console.log(res)
              that.setData({
                charge:true
              })
            })
          },
          fail (err) {
            console.error('pay fail', err)
          }
        })
      },
      fail: console.error,
    })


  },

  randomWord() {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    var nums = ""
    for (var i = 0; i < 32; i++) {
      var id = parseInt(Math.random() * 61)
      nums += chars[id]
    }
    return nums
  },

  dealFaceInfo: function (info) {
    const that=this;
    console.log(info)
    // 雷达图数据
    let list = [{
            'name': '光滑',
            'value': (info.skin.smooth / 4) * 100 + ''
        },
        {
            'name': '肤色',
            'value': (info.skin.color / 6) * 100 + ''
        },
        {
            'name': '痘痘',
            'value': info.acnespotmole.acbe_num == 0 ? "100" : (2.7 ** (-info.acnespotmole.acne_num)) * 100 + ''
        },
        {
            'name': '斑点',
            'value': (2.7 ** (-info.acnespotmole.speckle_num)) * 100 + ''
        },
        {
            'name': '皱纹',
            'value': (2.7 ** (-info.wrinkle.wrinkle_num)) * 100 + ''
        },
        {
            'name': '黑头',
            'value': info.blackheadpore.blackehead_num == 0 ? "100" : (2.7 ** (-info.blackheadpore.blackhead_num)) * 100 + ''
        },
    ]
    let radarList = {
        'name': '皮肤得分',
        list: list
    }

    // 各项指标评分
    let healthLevel = (info.acnespotmole.acbe_num == 0 ? 100 : (2.7 ** (-info.acnespotmole.acne_num)) * 100) * 0.5 +
        (2.7 ** (parseInt(-info.eyesattr.dark_circle_left.length == 0 ? 1 : -info.eyesattr.dark_circle_left[0].length)) +
            2.7 ** (parseInt(-info.eyesattr.dark_circle_right.length == 0 ? 1 : -info.eyesattr.dark_circle_right[0].length))
        ) / 2 * 100 * 0.25 +
        (2.7 ** parseInt(-info.eyesattr.eye_bags_left.length == 0 ? 0 : -info.eyesattr.eye_bags_left[0].length) +
            2.7 ** (parseInt(-info.eyesattr.eye_bags_right == 0 ? 0 : -info.eyesattr.eye_bags_right[0].length))) / 2 * 100 * 0.25
    let dryLevel = (1 - (info.skinquality.skin_dryoil_check.reduce((total, currentValue, index, arr) => {
        return total + parseInt(currentValue)
    }, 0) / 10)) * 100
    let smooth = ((info.skin.smooth / 4) * 100)
    let youngLevel = (2.7 * (-info.wrinkle.wrinkle_num)) + 100
    let score = (healthLevel + dryLevel + smooth + youngLevel) / 4

    let skinData = {
        "radarList": radarList,
        "score": score.toFixed(2),
        "healthLevel": healthLevel.toFixed(2),
        "smoothLevel": smooth.toFixed(2),
        "dryLevel": dryLevel.toFixed(2),
        "youngLevel": youngLevel,
        "count": this.data.count,
    }
    let issues=[]
    info.skin.smooth>=2?
    issues.push('光滑度')
    :'';//光滑
    // info.skin.color//肤色
    info.acnespotmole.acbe_num>0?
    issues.push("痘痘")
    :'';//痘痘
    info.speckle_num>0?
    issues.push("斑")
    :'';//斑
    info.wrinkle_num>0?
    issues.push("皱纹")
    :'';//皱纹
    info.blackheadpore.blackehead_num>0?
    issues.push("黑眼圈")
    :'';//黑眼圈
    this.setData({
        skinIssues:issues,
        skinData: skinData,
        skinGlobalData: this.data.skinGlobalData.concat(skinData)
    })
let condation;
condation={},
    db.collection('Goods').where({
      repair_effect:_.gt(3)
    }).orderBy('repair_effect', 'desc').limit(4).get({
      success:function (res){
      console.log(res)
      that.setData({
      ['tabs[0].content[0]']:res.data[0],
      ['tabs[0].content[1]']:res.data[1],
      ['tabs[1].content[0]']:res.data[2],
      ['tabs[1].content[1]']:res.data[3],
      })
    }
  })


},

selectHistory(){
  wx.navigateTo({
    url: '/pages/person/detectHistory/detectHistory',
  })
},


  // book: function (e) {
  //   let that = this
  //   wx.request({
  //     url: 'http://pv.sohu.com/cityjson?ie=utf-8',
  //     success:res=>{
  //       console.log(res)
  //       var aaa = res.data.split(' ');
  //       var bbb=aaa[4]
  //       var ccc = bbb.replace('"','')
  //       var ddd = ccc.replace('"', '')
  //       let ip = ddd.replace(',', '')



  //       let url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
  //       let options = {
  //         appid: "wx485412291c7b9227",
  //         mch_id: "1625399850",
  //         nonce_str: this.randomWord(),
  //         sign:"",
  //         body:"AI测肤",
  //         out_trade_no:this.randomWord(),
  //         total_fee:1,
  //         spbill_create_ip:ip,
  //         time_expire:"20200505220000"
  //       }
    
    
  //       wx.request({
  //         url: url,
  //         method: "POST",
  //         data: "",
  //         success: res => {
  //           console.log(res)
  //         },
  //         fail: err => {
  //           console.log(err)
  //         }
  //       })


  //     }
  //   })


  // },
  showDetail(e){
    wx.setClipboardData({
      data:e.currentTarget.dataset.goods.link
    })
    wx.showToast({
      // icon:"none",
      title: '复制商品链接',
      duration:1200
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  refuse(){
    wx.navigateBack({
      delta: 1,
    })
  },
  onTabsChange(e) {
    console.log('onTabsChange', e)
    const { key } = e.detail
    const index = this.data.tabs.map((n) => n.key).indexOf(key)

    this.setData({
      key,
      index,
    })
  },
  onSwiperChange(e) {
    console.log('onSwiperChange', e)
    const { current: index, source } = e.detail
    const { key } = this.data.tabs[index]

    if (!!source) {
      this.setData({
        key,
        index,
      })
    }
  }, 
})